<template>
  <div ref="player" id="dplayer"></div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted } from "vue";
import DPlayer from "dplayer";
import commonApi from "@/api/common";
import { getToken } from "@/utils/common";

const props = defineProps(["videoId"]);

let videoPlayer: DPlayer;
const player = ref(); // 获取标签对象，用于注入DPlayer播放器

// 设置视频的播放源
const init = (videoName: string) => {
  // @ts-ignore
  videoPlayer.switchVideo({
    url: commonApi.getVideo(videoName),
    // url: `/api/common/download/video/${fileName}`
  });
};
// 将init方法向上暴露给父组件，供其调用
defineExpose({ init });

onMounted(() => {
  videoPlayer = new DPlayer({
    container: player.value,
    screenshot: true, // 开启截图，如果开启，视频和视频封面需要允许跨域
    autoplay: true,
    lang: "zh-cn",
    hotkey: true, // 开启热键，支持快进、快退、音量控制、播放暂停
    volume: 0.7, // 默认音量，请注意播放器会记忆用户设置，用户手动设置音量后默认音量即失效
    video: {
      url: "",
    },
    danmaku: {
      id: props.videoId,
      api: "/api/bullet/",
      // @ts-ignore
      token: getToken(),
      // addition: ["https://s-sh-17-dplayercdn.oss.dogecdn.com/1678963.json"]
    },
  });

});
// 销毁播放器
onUnmounted(() => {
  videoPlayer.destroy();
});
</script>

<style lang="scss">
#dplayer {
  border-radius: 10px;
  box-shadow: 0 0 10px #343434;
  width: 100%;
  height: 100%;
}

/* 顶部弹幕和底部弹幕的水平位置，使其能够居中 */
.dplayer-danmaku-bottom,
.dplayer-danmaku-top {
  left: 0;
}
</style>
